package com.bjpowernode.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.bjpowernode.mapper.TClueMapper;
import com.bjpowernode.query.ClueExcel;
import jakarta.annotation.Resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * easy excel读取监听器
 */
public class ClueExcelListener implements ReadListener<ClueExcel> {

    /**
     * 在内存中读取到100条数据时，一次性批量存储到数据库中
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 定义缓存  存储读取的excel数据
     */
    private List<ClueExcel> clueDataList = new ArrayList<>(BATCH_COUNT);


    /**
     * 当前类没有交给spring容器管理，所以这里不能直接注入
     */
    private TClueMapper tClueMapper;

    private Integer loginUserId;

    public ClueExcelListener(TClueMapper tClueMapper, Integer loginUserId) {
        this.tClueMapper = tClueMapper;
        this.loginUserId = loginUserId;
    }

    /**
     * 读取到一行数据，就会执行一次该方法
     * @param clueExcel
     * @param analysisContext
     */
    @Override
    public void invoke(ClueExcel data, AnalysisContext analysisContext) {
        data.setCreateBy(loginUserId);
        data.setCreateTime(new Date());

        clueDataList.add(data);

        //判断是否需要添加数据库
        if (clueDataList.size() >= BATCH_COUNT){
            //添加到数据库中
            tClueMapper.saveExcel(clueDataList);

            //清空缓存 weblogic  达梦  人大金仓   仓颉
            clueDataList = new ArrayList<>(BATCH_COUNT);
        }
    }


    /**
     * excel解析完毕后执行1次该方法
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //添加到数据库中
        tClueMapper.saveExcel(clueDataList);
    }
}
